/**
 * Copyright 2011 Adrian Witas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.abstractmeta.commandify.core.command;

import org.abstractmeta.commandify.Commandify;
import org.abstractmeta.commandify.command.Commands;
import org.abstractmeta.commandify.core.AbstractCommandify;
import org.abstractmeta.commandify.core.command.map.MapCommands;
import org.abstractmeta.commandify.core.command.util.CommandifyUtil;

import java.util.*;

/**
 * Represents a map which implements commandify.
 * This enables all mutable map method calls being encapsulated as method command.
 * If either k or value implement commandify then as long as it is possible to build cloned version by commandify, it will be used
 * instead of actual k or v instance value.
 *
 * @author Adrian Witas
 */
public class CommandifyMap<K, V> extends AbstractCommandify<Map<K, V>> implements Map<K, V>, Commandify<Map<K, V>> {

    private final Map<K, V> map;


    public CommandifyMap(Map<K, V> map) {
        super(Map.class, new MapCommands<Map<K, V>>(Map.class));
        this.map = map;
        addConstructorCommand();
        commandifyExistingMapItems();
    }





    protected void commandifyExistingMapItems() {
        Commands<Map<K, V>> commands = getCommands();
        for (Map.Entry<K, V> entry : map.entrySet()) {
            commands.add(getPutCommand(entry.getKey(), entry.getValue()));
        }
    }

    protected void addConstructorCommand() {
        getCommands().setConstructorCommand(new AbstractConstructorCommand<Map<K, V>>() {
            @Override
            public Map<K, V> execute() {
                return new HashMap<K, V>();
            }
        });


    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean containsKey(Object o) {
        return map.containsKey(o);
    }

    @Override
    public boolean containsValue(Object o) {
        return map.containsValue(o);
    }

    @Override
    public V get(Object o) {
        return map.get(o);
    }

    @Override
    public V put(K k, V v) {
        getCommands().add(getPutCommand(k, v));
        CommandifyUtil.associateAccessor(v, this, k);
        return map.put(k, v);
    }




    protected AbstractMethodCommand<Map<K, V>> getPutCommand(final K k, final V v) {
        return new AbstractMethodCommand<Map<K, V>>("put", new Class[]{k.getClass(), v.getClass()}, new Object[]{k, v}) {

            @Override
            public void execute(Map<K, V> instance) {

                V value = getCommandValue(v);
                instance.put(getCommandValue(k), value);
            }

        };
    }


    @Override
    public V remove(final Object o) {
        getCommands().add(new AbstractMethodCommand<Map<K, V>>("remove", new Class[]{o.getClass()}, new Object[]{o}) {
            @Override
            public void execute(Map<K, V> instance) {

                instance.remove(o);
            }
        });
        V result =  map.remove(o);
        CommandifyUtil.dissociateAccessor(result);
        return result;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> map) {
        for (K key : map.keySet()) {
            this.map.put(key, map.get(key));
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void clear() {
        getCommands().add(new AbstractMethodCommand<Map<K, V>>("clear") {
            @Override
            public void execute(Map<K, V> instance) {
                instance.clear();
            }
        });
        CommandifyUtil.dissociateAccessor(map.values());
        map.clear();
    }

    @Override
    public Set<K> keySet() {
        return map.keySet();
    }

    @Override
    public Collection<V> values() {
        return map.values();
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        return map.entrySet();
    }


}
